package eventplanner.ejb.adders;

import eventplanner.ejb.dao.EventDao;
import eventplanner.entities.*;
import eventplanner.validation.URL;
import eventplanner.validation.URLValidator;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;

import static org.junit.Assert.assertEquals;

@RunWith(Arquillian.class)
public class TagsAdderIT {

	@Deployment
	public static Archive<?> createTestArchive() {
		return ShrinkWrap.create(WebArchive.class, "test.war")
				.addClasses(TagsAdder.class, Feed.class, Event.class, Doelgroep.class, Event_.class, Identifiable.class,
						URL.class, URLValidator.class, EventType.class, EventDao.class)
						// enable JPA
				.addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
						// enable CDI
				.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
						// Deploy our test datasource
				.addAsWebInfResource("test-ds.xml", "test-ds.xml");
	}

	@Inject
	private TagsAdder tagsAdder;

	@PersistenceContext
	private EntityManager em;

	@Inject
	private UserTransaction transaction;

	@Test
	public void testInsertionAndRetrieval() throws Exception {

		transaction.begin();
		em.joinTransaction();

		List<Event> existingEvents = em.createQuery("select e from Event e", Event.class).getResultList();
		assertEquals(0, existingEvents.size());

		Event event = createEventWithTags(Arrays.asList("school", "ict", "java"));
		em.persist(event);

		List<Event> list = tagsAdder.readWithTags(new HashSet<>(Arrays.asList("ict")));

		assertEquals(1, list.size());
		assertEquals(event.getId(), list.get(0).getId());

		list = tagsAdder.readWithTags(new HashSet<>(Arrays.asList("ict", "java")));

		assertEquals(1, list.size());
		assertEquals(event.getId(), list.get(0).getId());

		transaction.rollback();
	}

	private Event createEventWithTags(List<String> tags) {
		Event event = new Event();
		event.setTitle("Test Title");
		event.setDescription("Test Description");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		event.setStart(calendar.getTime());
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		event.setEnd(calendar.getTime());

		event.setTags(tags);
		return event;
	}
}
